<template>
  <view class="signin-container">
    <!-- 签到日历 -->
    <view class="calendar-section">
      <view class="calendar-header">
        <view class="month-title">{{ currentYear }}年{{ currentMonth }}月</view>
        <view class="calendar-actions">
          <view class="prev-month" @click="changeMonth(-1)">
            <u-icon name="arrow-left" size="40" color="#333"></u-icon>
          </view>
          <view class="next-month" @click="changeMonth(1)">
            <u-icon name="arrow-right" size="40" color="#333"></u-icon>
          </view>
        </view>
      </view>
      
      <view class="calendar-body">
        <!-- 星期标题 -->
        <view class="week-header">
          <view class="week-day" v-for="(day, index) in weekDays" :key="index">{{ day }}</view>
        </view>
        
        <!-- 日期格子 -->
        <view class="days-grid">
          <view 
            class="day-cell" 
            v-for="(day, index) in daysArray" 
            :key="index"
            :class="{
              'empty': !day.date,
              'today': day.isToday,
              'signed': day.isSigned,
              'disabled': day.isDisabled
            }"
          >
            <view class="day-number" v-if="day.date">{{ day.date }}</view>
            <view class="sign-mark" v-if="day.isSigned">
              <u-icon name="checkmark" size="24" color="#ffffff"></u-icon>
            </view>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 签到信息 -->
    <view class="signin-info">
      <view class="info-item">
        <view class="info-label">连续签到</view>
        <view class="info-value">{{ signInfo.continuous || 0 }}天</view>
      </view>
      <view class="info-item">
        <view class="info-label">本月签到</view>
        <view class="info-value">{{ signInfo.monthly || 0 }}天</view>
      </view>
      <view class="info-item">
        <view class="info-label">总签到天数</view>
        <view class="info-value">{{ signInfo.total || 0 }}天</view>
      </view>
    </view>
    
    <!-- 签到规则 -->
    <view class="signin-rules">
      <view class="rules-title">签到规则</view>
      <view class="rules-content">
        <view class="rule-item">1. 每日签到可获得{{ signRule.basic }}积分</view>
        <view class="rule-item">2. 连续签到7天额外奖励{{ signRule.week }}积分</view>
        <view class="rule-item">3. 连续签到30天额外奖励{{ signRule.month }}积分</view>
        <view class="rule-item">4. 每日签到时间为00:00-23:59</view>
      </view>
    </view>
    
    <!-- 签到按钮 -->
    <view class="signin-action">
      <u-button 
        type="primary" 
        :disabled="isSigned" 
        @click="handleSignin"
      >{{ isSigned ? '今日已签到' : '立即签到' }}</u-button>
    </view>
    
    <!-- 签到成功弹窗 -->
    <u-popup v-model="showSignSuccess" mode="center" border-radius="16" width="600rpx">
      <view class="sign-success-popup">
        <view class="success-icon">
          <u-icon name="checkmark-circle" color="#5ac725" size="80"></u-icon>
        </view>
        <view class="success-title">签到成功</view>
        <view class="success-desc">恭喜获得{{ earnedPoints }}积分</view>
        <view class="success-tips" v-if="continuousDays > 1">已连续签到{{ continuousDays }}天</view>
        <view class="success-action">
          <u-button type="primary" @click="showSignSuccess = false">我知道了</u-button>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
import { user } from '@/api/cms'

export default {
  data() {
    return {
      weekDays: ['日', '一', '二', '三', '四', '五', '六'],
      currentYear: new Date().getFullYear(),
      currentMonth: new Date().getMonth() + 1,
      daysArray: [],
      signedDays: [], // 已签到的日期数组，格式为 ['2023-01-01', '2023-01-02']
      isSigned: false, // 今日是否已签到
      signInfo: {
        continuous: 0, // 连续签到天数
        monthly: 0, // 本月签到天数
        total: 0 // 总签到天数
      },
      signRule: {
        basic: 5, // 每日签到基础积分
        week: 10, // 连续签到7天额外奖励
        month: 50 // 连续签到30天额外奖励
      },
      showSignSuccess: false,
      earnedPoints: 0,
      continuousDays: 0
    }
  },
  onLoad() {
    this.initCalendar()
    this.getSigninInfo()
  },
  methods: {
    // 初始化日历
    initCalendar() {
      this.generateDaysArray()
    },
    
    // 生成日期数组
    generateDaysArray() {
      const year = this.currentYear
      const month = this.currentMonth
      
      // 获取当月第一天是星期几
      const firstDay = new Date(year, month - 1, 1).getDay()
      
      // 获取当月天数
      const daysInMonth = new Date(year, month, 0).getDate()
      
      // 获取今天日期
      const today = new Date()
      const isCurrentMonth = today.getFullYear() === year && today.getMonth() + 1 === month
      const currentDate = today.getDate()
      
      // 生成日期数组
      this.daysArray = []
      
      // 填充前面的空白
      for (let i = 0; i < firstDay; i++) {
        this.daysArray.push({
          date: null,
          isToday: false,
          isSigned: false,
          isDisabled: true
        })
      }
      
      // 填充日期
      for (let i = 1; i <= daysInMonth; i++) {
        const dateStr = `${year}-${month.toString().padStart(2, '0')}-${i.toString().padStart(2, '0')}`
        this.daysArray.push({
          date: i,
          isToday: isCurrentMonth && i === currentDate,
          isSigned: this.signedDays.includes(dateStr),
          isDisabled: new Date(year, month - 1, i) > today
        })
      }
    },
    
    // 切换月份
    changeMonth(offset) {
      let newMonth = this.currentMonth + offset
      let newYear = this.currentYear
      
      if (newMonth > 12) {
        newMonth = 1
        newYear++
      } else if (newMonth < 1) {
        newMonth = 12
        newYear--
      }
      
      this.currentMonth = newMonth
      this.currentYear = newYear
      
      this.generateDaysArray()
      this.getSigninInfo()
    },
    
    // 获取签到信息
    async getSigninInfo() {
      try {
        const { data } = await user.getUserSigned()
        
        if (data.code === 1) {
          this.isSigned = data.data.signed
          this.signInfo = data.data.signInfo
          this.signedDays = data.data.signedDays || []
          
          // 更新日历中的签到状态
          this.generateDaysArray()
        } else {
          uni.showToast({
            title: data.msg || '获取签到信息失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('获取签到信息失败', error)
        uni.showToast({
          title: '获取签到信息失败，请稍后再试',
          icon: 'none'
        })
      }
    },
    
    // 执行签到
    async handleSignin() {
      if (this.isSigned) {
        uni.showToast({
          title: '今日已签到',
          icon: 'none'
        })
        return
      }
      
      try {
        const { data } = await user.userSignin()
        
        if (data.code === 1) {
          // 更新签到状态
          this.isSigned = true
          
          // 更新签到信息
          this.signInfo = data.data.signInfo
          
          // 更新签到日期数组
          const today = new Date()
          const dateStr = `${today.getFullYear()}-${(today.getMonth() + 1).toString().padStart(2, '0')}-${today.getDate().toString().padStart(2, '0')}`
          this.signedDays.push(dateStr)
          
          // 更新日历
          this.generateDaysArray()
          
          // 显示签到成功弹窗
          this.earnedPoints = data.data.points || this.signRule.basic
          this.continuousDays = this.signInfo.continuous
          this.showSignSuccess = true
        } else {
          uni.showToast({
            title: data.msg || '签到失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('签到失败', error)
        uni.showToast({
          title: '签到失败，请稍后再试',
          icon: 'none'
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.signin-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 20rpx;
}

.calendar-section {
  background-color: #ffffff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.calendar-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
  
  .month-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333333;
  }
  
  .calendar-actions {
    display: flex;
    
    .prev-month, .next-month {
      padding: 0 20rpx;
    }
  }
}

.week-header {
  display: flex;
  margin-bottom: 20rpx;
  
  .week-day {
    flex: 1;
    text-align: center;
    font-size: 28rpx;
    color: #999999;
  }
}

.days-grid {
  display: flex;
  flex-wrap: wrap;
  
  .day-cell {
    width: 14.28%;
    height: 80rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative;
    margin-bottom: 10rpx;
    
    &.empty {
      background-color: transparent;
    }
    
    &.today {
      .day-number {
        color: #3c9cff;
        font-weight: bold;
      }
    }
    
    &.signed {
      .day-number {
        color: #ffffff;
      }
      
      &::after {
        content: '';
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        width: 60rpx;
        height: 60rpx;
        background-color: #5ac725;
        border-radius: 50%;
        z-index: -1;
      }
    }
    
    &.disabled {
      .day-number {
        color: #cccccc;
      }
    }
    
    .day-number {
      font-size: 28rpx;
      color: #333333;
      z-index: 1;
    }
  }
}

.signin-info {
  background-color: #ffffff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  display: flex;
  justify-content: space-around;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  
  .info-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    
    .info-label {
      font-size: 28rpx;
      color: #666666;
      margin-bottom: 10rpx;
    }
    
    .info-value {
      font-size: 36rpx;
      font-weight: bold;
      color: #3c9cff;
    }
  }
}

.signin-rules {
  background-color: #ffffff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  
  .rules-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333333;
    margin-bottom: 20rpx;
  }
  
  .rule-item {
    font-size: 28rpx;
    color: #666666;
    line-height: 1.8;
  }
}

.signin-action {
  padding: 0 30rpx;
}

.sign-success-popup {
  padding: 40rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  
  .success-icon {
    margin-bottom: 20rpx;
  }
  
  .success-title {
    font-size: 36rpx;
    font-weight: bold;
    color: #333333;
    margin-bottom: 20rpx;
  }
  
  .success-desc {
    font-size: 32rpx;
    color: #f56c6c;
    margin-bottom: 10rpx;
  }
  
  .success-tips {
    font-size: 28rpx;
    color: #666666;
    margin-bottom: 30rpx;
  }
  
  .success-action {
    width: 100%;
  }
}
</style>